package org.scohen.juploadr.util;

import java.util.Map;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;

public class HttpUtils {
    private static URLCodec codec = new URLCodec();

    public static String mapToQueryString(Map<String, String> params) {
        StringBuffer url = new StringBuffer("?");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            char lastChar = url.charAt(url.length() - 1);
            if (lastChar != '&' && lastChar != '?') {
                url.append("&"); //$NON-NLS-1$
            }
            url.append(entry.getKey());
            url.append("="); //$NON-NLS-1$
            url.append(encode(entry.getValue()));
        }
        return url.toString();
    }

    protected static String encode(String toEnc) {
        try {
            return codec.encode(toEnc);
        } catch (EncoderException e) {

        }
        return null;
    }
}
